package org.jetnuke.modules.admin.stories;

import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;

public class NewsResources implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(NewsResources.class);

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		String dir_ = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
				+ "/news/";
		File f = new File(dir_);
		ArrayList resList = new ArrayList();
		if (f.exists() && f.isDirectory()) {
			String strs[] = f.list();
			resList = new ArrayList();
			if (strs != null) {
				for (int i = 0; i < strs.length; i++) {
					File dir = new File(f, strs[i]);
					if (!dir.isDirectory())
						resList.add(strs[i]);
				}
			}
		}

		Iterator it = resList.iterator();
		ArrayList list = new ArrayList();
		while (it.hasNext()) {
			String fileName = (String) it.next();
			List intList = new ArrayList();
			intList.add(fileName);
			// Accented letters don't work. Any solutions?
			String encodedName = fileName;// URLUTF8Encoder.encode(fileName).replaceAll("\\+","%20");
			intList.add(encodedName);

			String tmp = encodedName.toLowerCase();
			if (tmp.endsWith(".png") || tmp.endsWith(".gif")
					|| tmp.endsWith(".jpg") || tmp.endsWith(".jpeg")) {
				intList.add("image");
			} else {
				intList.add("else");
			}

			list.add(intList);
		}
		vc.put("ls", list);
		ActionForward returnActionForward = new ActionForward(op, info);
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return returnActionForward;
	}

}
